#include "tlv.h"

int tlv_add(char *buf, int *offset, int t, int l, char *v)
{
	memcpy(buf+(*offset), (char *)&t, sizeof(t));
	*offset += sizeof(t);

	memcpy(buf+(*offset), (char *)&l, sizeof(l));
	*offset += sizeof(l);

	memcpy(buf+(*offset), v, l);
	*offset += l;

	return 0;
}

int tlv_get(char *buf, int buf_len, int t, int *l, char **v)
{
	int offset = 0;
	while (offset < buf_len) {
		int tmp_T = 0;
		int tmp_L = 0;
		tmp_T = *((int *)(buf+offset));
		offset += sizeof(t);

		tmp_L = *((int *)(buf+offset));
		offset += sizeof(tmp_L);

		if (tmp_T != t) {
			offset += tmp_L;
			continue;
		}
		
		if (!(*v)) {
			*v = (char *)malloc(sizeof(tmp_L+4));
			memset(*v, 0, tmp_L+4);
			
			memcpy(*v, buf+offset, tmp_L);
			if (l) {
				*l = tmp_L;
			}
			offset += tmp_L;

			return 0;
		}
	}

	return -1;
}
